package c5_1;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

/**
 * @author： pang-yun
 * @date： 2021-09-06 15:48
 * 功能目的 ：用于
 */
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(32);
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8100));

        ArrayList<SocketChannel> channelArrayList = new ArrayList<>();

        while (true) {
            log.info("connecting........");
            SocketChannel accept = ssc.accept();
            log.info("connected {}", accept);

            channelArrayList.add(accept);

            for (SocketChannel sc : channelArrayList){

                    sc.read(byteBuffer);


                byteBuffer.flip();
                while (byteBuffer.hasRemaining()){
                    byte b = byteBuffer.get();
                    System.out.print((char) b);
                }
                byteBuffer.clear();
            }

            System.out.println("==========");
           /* channelArrayList.stream().forEach(channel -> {
                try {
                    log.info("BeforeRead.....{}", accept);
                    channel.read(byteBuffer);
                    byteBuffer.flip();
                    while (byteBuffer.hasRemaining()) {
                        byte b = byteBuffer.get();
                        System.out.print((char) b);
                    }
                    byteBuffer.clear();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });*/
        }


    }
}
